/*****************************************************************************
 * HUSONG PROPRIETARY INFORMATION
 * <p/>
 * The information contained herein is proprietary to HUSONG
 * and shall not be reproduced or disclosed in whole or in part
 * or used for any design or manufacture
 * without direct written authorization from HUSONG.
 * <p/>
 * Copyright (c) 2015 by HUSONG.  All rights reserved.
 *****************************************************************************/
package com.crp.broker.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.crp.broker.model.UserBean;
import com.crp.broker.service.IUserService;
import com.crp.redis.service.IRedisService;

/**
 * 
 */
@Controller
@RequestMapping("/broker")
public class IndexController {
    @Autowired
    private IUserService iUserService;

    @Autowired
    private IRedisService iRedisService;

    @Resource
    private AmqpTemplate amqpTemplate;

    private Logger logger = LoggerFactory.getLogger(IndexController.class);

    public void sendMessage(Object message) {
        logger.info("to send message:{}", message);
        amqpTemplate.convertAndSend("queueTestKey", message);
    }

    @RequestMapping("/index")
    public ModelAndView index(long uid, HttpServletResponse response) {
        String html = "<html><head><script type='text/javascript'>alert('hello world');</script><script type='text/javascript' src='xxx.js'></script></head><body></body><html> ";
        Document doc = Jsoup.parse(html);
        Elements scripts = doc.select("script");
        for (Element script : scripts) {
                String type = script.attr("type");
                String language = script.attr("language");
                if((StringUtils.isEmpty(type) || type.equals("text/javascript")) &&
                         (StringUtils.isEmpty(language) || language.equals("javascript"))){
                    String src=script.attr("src");
                    String innerScript=script.html();
                    System.out.println("innerScript:"+innerScript);
                    System.out.println("src:"+src);
                }
            }
        
        ModelAndView model=new ModelAndView("/test.html");
         System.out.println(uid);
         sendMessage("***********"+uid+"************");
         UserBean bean = iUserService.getUserById(uid);
         PrintWriter out;
         try {
         out = response.getWriter();
         out.write(bean.getName() + ":" + bean.getAge());
         } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
         }
         return model;
        
    }
    
    public static String removeEvents(String content){

        String regx="(<[^<]*)(on\\w*\\x20*=|javascript:)";
        Pattern pattern = Pattern.compile(regx, Pattern.CASE_INSENSITIVE+Pattern.MULTILINE);// 不区分大小写
        Matcher matcher ;
        String ts= content;
        //此处需要循环匹配，防止恶意构造的字符串如 onclick=onclick=XXX
        while((matcher=pattern.matcher(ts)).find()){
            ts= matcher.replaceAll("$1");
        }
        return ts;
    }

    /**
     * @param html
     *            提取单个html文件内嵌和引用的全部js
     *            如果有多个script包含内嵌js，程序会首先把这些js源码连接成一个字符串以html绝对路径为key保存到返回值
     *            引用的js文件源码，以js绝对路径为key，源码为值保存到返回结果
     * */
    // public static Map<String,String> extractJsFromHtml(File html) throws
    // MalformedURLException, IOException {
    // PrintWriter pw=null;
    // try{
    // CodeDetectUtil.initCodeDetector();
    // Document htmldoc=DataUtil.load(html, CodeDetectUtil.detectCharset(html),
    // html.toURI().getPath());
    // Elements scripts=htmldoc.select("script");
    // Map<String,String> jscode=new HashMap<String,String>();
    // StringWriter sw=new StringWriter();
    // pw=new PrintWriter(sw);
    // for(Element script : scripts){
    // String type=script.attr("type");
    // String language=script.attr("language");
    // if((Help.isEmpty(type) || type.equals("text/javascript")) &&
    // (Help.isEmpty(language) || language.equals("javascript"))){
    // String src=script.attr("src");
    // if(Help.isEmpty(src)){
    // pw.println(script.html().trim());
    // }else{
    // File jsfile=null;
    // if(src.startsWith(JsChecker.uriPrefix)){
    // jsfile=new
    // File(Help.isEmpty(webappPath)?html.getParent():webappPath,src.substring(JsChecker.uriPrefix.length()));
    // }else{
    // jsfile=new File(html.getParentFile(),src);
    // }
    // jscode.put(jsfile.getAbsolutePath(),FileUtil.loadTxt(jsfile,
    // CodeDetectUtil.detectCharset(jsfile)));
    // }
    // }
    // }
    // pw.flush();
    // jscode.put(html.getAbsolutePath(),sw.toString());
    // return jscode;
    // }finally{
    // CodeDetectUtil.endCodeDetector();
    // }
    // }

}
